package com.example.pt.service;

import com.example.pt.repository.*;
import com.example.pt.entity.*;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class TorrentFileService {

    @Autowired
    private TorrentFileRepository torrentFileRepository;

    @Autowired
    private TorrentFileESRepository esRepository;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private TorrentInfoHashService torrentInfoHashService;

    // Add new method for file upload
    public TorrentFile uploadTorrentFile(String fileUrl, int uid, String title,
                                         int category, String format, String language,
                                         String description,long fileSize) throws IOException {

//          Create TorrentFile object
        TorrentFile torrentFile = new TorrentFile();
        torrentFile.setUid(uid);
        torrentFile.setTitle(title);
        torrentFile.setCategory(category);
        torrentFile.setFormat(format);
        torrentFile.setLanguage(language);
        torrentFile.setDescription(description);
        torrentFile.setFileUrl(fileUrl);
        torrentFile.setFileSize(fileSize);
        torrentFile.setUploadTime(new Timestamp(System.currentTimeMillis()).toLocalDateTime());
        torrentFile.setDownloadCount(0);
        torrentFile.setViewCount(0);
        torrentFile.setStatus(0);

        TorrentFile savedTorrentFile = torrentFileRepository.save(torrentFile);

        syncToES(savedTorrentFile);

        return savedTorrentFile;
    }

    public List<TorrentFile> getAllTorrentFiles() {
        return torrentFileRepository.findAll();
    }

    public Optional<TorrentFile> getTorrentFileByTid(int tid) {
        return torrentFileRepository.findByTid(tid);
    }

    public List<TorrentFile> getTorrentFilesByUser(int uid) {
        return torrentFileRepository.findByUid(uid);
    }


    public List<TorrentFile> getTorrentFilesByCategory(int category) {
        return torrentFileRepository.findByCategory(category);
    }

    public List<TorrentFile> getTorrentFilesByStatus(int status) {
        return torrentFileRepository.findByStatus(status);
    }

    public List<TorrentFile> searchTorrentFiles(String keyword) {
        return torrentFileRepository.findByTitleContaining(keyword);
    }

//    public TorrentFile saveTorrentFile(TorrentFile torrentFile) {
//        if (torrentFile.getUploadTime() == null) {
//            torrentFile.setUploadTime(new Date());
//        }
//        return torrentFileRepository.save(torrentFile);
//    }

    public TorrentFile updateTorrentFile(TorrentFile torrentFile) {
        TorrentFile updatedTorrentFile = torrentFileRepository.save(torrentFile);
        syncToES(updatedTorrentFile);
        return updatedTorrentFile;
    }

    public void deleteTorrentFile(int tid) {
        torrentFileRepository.deleteById(tid);
        esRepository.deleteById(tid);
    }

    public TorrentFile updateStatus(int tid, int status) {
        Optional<TorrentFile> optionalFile = torrentFileRepository.findById(tid);
        if (optionalFile.isPresent()) {
            TorrentFile file = optionalFile.get();
            file.setStatus(status);
            TorrentFile updateTorrentFile = torrentFileRepository.save(file);
            syncToES(updateTorrentFile);
            return updateTorrentFile;
        }
        return null;
    }

    public TorrentFile incrementDownloadCount(int tid) {
        Optional<TorrentFile> optionalFile = torrentFileRepository.findById(tid);
        if (optionalFile.isPresent()) {
            TorrentFile file = optionalFile.get();
            file.setDownloadCount(file.getDownloadCount() + 1);
            TorrentFile updatedFile = torrentFileRepository.save(file);
            syncToES(updatedFile);
            return updatedFile;
        }
        return null;
    }

    public TorrentFile incrementViewCount(int tid) {
        Optional<TorrentFile> optionalFile = torrentFileRepository.findById(tid);
        if (optionalFile.isPresent()) {
            TorrentFile file = optionalFile.get();
            file.setViewCount(file.getViewCount() + 1);
            TorrentFile updatedFile = torrentFileRepository.save(file);
            syncToES(updatedFile);
            return updatedFile;
        }
        return null;
    }


    public TorrentFile updateTorrentFile(int tid, int uid,
                                         String title, int category,
                                         String format, String language,
                                         String description,
                                         String savedFileName, long fileSize,
                                         int status) throws Exception {

        TorrentFile file = torrentFileRepository.findById(tid)
                .orElseThrow(() -> new Exception("文件不存在"));

        if (file.getUid() != uid) {
            throw new Exception("无权限修改此文件");
        }

        boolean changed = false;

        if (!Objects.equals(file.getTitle(), title)) {
            file.setTitle(title);
            changed = true;
        }

        if (!Objects.equals(file.getCategory(), category)) {
            file.setCategory(category);
            changed = true;
        }

        if (!Objects.equals(file.getFormat(), format)) {
            file.setFormat(format);
            changed = true;
        }

        if (!Objects.equals(file.getLanguage(), language)) {
            file.setLanguage(language);
            changed = true;
        }

        if (!Objects.equals(file.getDescription(), description)) {
            file.setDescription(description);
            changed = true;
        }

        if (savedFileName != null) {
            file.setFileUrl(savedFileName);
            file.setFileSize(fileSize);
            changed = true;
        }
        //不更新上传时间
        //设置待审核
        file.setStatus(status);

        TorrentFile updatedTorrentFile = torrentFileRepository.save(file);
        syncToES(updatedTorrentFile);

//        if (changed) {
//            file.setUploadTime(new Date());
//        }
        return updatedTorrentFile;
    }

    private void syncToES(TorrentFile torrentFile) {
        int tid = torrentFile.getTid();

        // 转换为 ES 实体，并设置 tid（ES 会将 @Id 字段作为文档 _id）
        TorrentFileES esTorrent = modelMapper.map(torrentFile, TorrentFileES.class);

        System.out.println("tid/**************"+tid);
        esTorrent.setTid(tid); // 确保 tid 正确传递（如果映射工具未自动处理）

        // 保存到 ES 时，tid 会作为 _id
        esRepository.save(esTorrent);
    }


    public TorrentFile uploadTorrentFileTest(String fileUrl, int uid, String title,
                                             int category, String format, String language,
                                             String description,long fileSize) throws IOException {
        TorrentFile torrentFile = new TorrentFile();
        torrentFile.setUid(uid);
        torrentFile.setTitle(title);
        torrentFile.setCategory(category);
        torrentFile.setFormat(format);
        torrentFile.setLanguage(language);
        torrentFile.setDescription(description);
        torrentFile.setFileUrl(fileUrl);
        torrentFile.setFileSize(fileSize);
        torrentFile.setUploadTime(new Timestamp(System.currentTimeMillis()).toLocalDateTime());
        torrentFile.setDownloadCount(0);
        torrentFile.setViewCount(0);
        torrentFile.setStatus(1);


        TorrentFile savedFile = torrentFileRepository.save(torrentFile);

        syncToES(savedFile);

        return savedFile;
    }

    /**
     * 根据种子ID获取InfoHash
     * @param tid 种子ID
     * @return InfoHash字符串
     */
    public String getInfoHashByTid(int tid) {
        return torrentInfoHashService.getInfoHashByTid(tid);
    }

}